package com.example.mcu_up.serial;

import android.util.Log;

public class CRC16 {
	private static short[] crcTable = new short[256];
	private static int gPloy = 0x8408; // 生成多项式

	private static short getCrcOfByte(int aByte) {
		int value = aByte << 8;

		for (int count = 7; count >= 0; count--) {
			if ((value & 0x8000) != 0) { // 高第16位为1，可以按位异或
				value = (value << 1) ^ gPloy;
			} else {
				value = value << 1; // 首位为0，左移
			}

		}
		value = value & 0xFFFF; // 取低16位的值
		return (short) value;
	}

	public static short getCrc(byte[] data) {
		int crc = 0;
		int length = data.length;

		for (int i = 0; i < 256; i++) {
			crcTable[i] = getCrcOfByte(i);
		}
		for (int i = 0; i < length; i++) {
			crc = ((crc & 0xFF) << 8)
					^ crcTable[(((crc & 0xFF00) >> 8) ^ data[i]) & 0xFF];
		}
		crc = crc & 0xFFFF;
		return (short) crc;
	}

	public static short getCheckSum(byte[] data) {
		short sum = 0;
		int n = data.length - 1;
		for (int i = 0; i < n; i++) {
			sum += data[i];
		}
		return (short) (1 + ~sum);
	}

	public static int CyBtldr_ComputeChecksumCrc16(byte[] buf, int size) {

		int crc = (int) 0xffff;
		int tmp;

		if (size == 0)
			return (int) (~crc);

		int i = 0;
		int j = 0;
		do {
			for (i = 0, tmp = (int) (0x00ff & buf[j]); i < 8; i++, tmp >>= 1) {
				if (((crc & 0x0001) ^ (tmp & 0x0001)) != 0)
					crc = (int) ((crc >> 1) ^ 0x8408);
				else
					crc >>= 1;
				;
			}
			j++;
		} while (--size != 0);

		crc = (int) (~crc & 0xFFFF);
		tmp = crc;
		crc = (int) ((crc << 8) | (tmp >> 8 & 0x00FF));
		return (int) crc & 0x0000ffff;
	}

	public static int CyBtldr_ComputeChecksum(byte[] buf, int size) {
		int sum = 0;
		for (int i = 0; i < size; i++)
			sum += buf[i] & 0x00ff;

		Log.i("checksum", String.valueOf((int) (1 + ~sum) + 0xffff));
		return (int) ((1 + ~sum));

	}

}
